package com.fyyg.common.aliyun.oss;

import com.aliyun.oss.OSSClient;

import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 * OSS上传文件工具类
 *
 * @author hang.ouyang
 * @date 2016-04-06 16:58
 */
public class OSSFileUploadUtil {
    private final static Logger logger = LogManager.getLogger(OSSFileUploadUtil.class);

    public static String uploadFile(InputStream inputStream, String fileName){
        OSSClient client = new OSSClient(OSSObject.ENDPOINT,OSSObject.ACCESSKEYID,OSSObject.ACCESSKEYSECRET);
        try {
            String  relativePath = relativePath(fileName);
            client.putObject(OSSObject.BUCKETNAME,relativePath,inputStream);
            return relativePath;
        }catch (Exception e){
            logger.error("Upload file fail"+e.getLocalizedMessage());
            return null;
        }finally {
            client.shutdown();
        }
    }

    public static String uploadFile(File file,String fileName){
        OSSClient client = new OSSClient(OSSObject.ENDPOINT,OSSObject.ACCESSKEYID,OSSObject.ACCESSKEYSECRET);
        try {
            String  relativePath = relativePath(fileName);
            InputStream inputStream = new FileInputStream(file);
            client.putObject(OSSObject.BUCKETNAME,relativePath,inputStream);
            return relativePath;
        } catch (FileNotFoundException e) {
            logger.error("Upload file fail"+e.getLocalizedMessage());
            return null;
        }finally {
            client.shutdown();
        }
    }

    public static String uploadFile(String localFilePath,String fileName){
        return uploadFile(new File(localFilePath),fileName);
    }

    private static String relativePath(String fileName ){
        String relativePath = OSSObject.ROOT_IMAGE_DIR;
        if (relativePath.indexOf("/") == 0) {
            relativePath = relativePath.substring(1);
        }
        if (relativePath.indexOf("/") != relativePath.length() - 1) {
            relativePath = relativePath + "/";
        }
       return relativePath+fileName;
    }
    
   



    public static void main(String[] args) {
        //image/acv.jpg
        String relativePath =  OSSFileUploadUtil.uploadFile("D:\\1.jpg","20160512/logo.jpg");
        //拼接外网路径
        String overPath = OSSImageUrlUtil.converToOverallPath(relativePath);
        System.out.println(relativePath+"\t=="+overPath);
    }



}
